<template>
  <div class="app-container">
    <nabars index="1"></nabars>

    <topIndex style="margin-bottom: 20px;" :indexCount="indexCount"></topIndex>

    <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="80px">
      <div class="from-item">
        <el-form-item label="微信名称" prop="wcName">
          <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入微信名称" clearable />
        </el-form-item>
        <el-form-item label="助手名称" prop="nickName">
          <el-input v-model="queryParams.nickName" @keyup.enter.native="handleQuery" placeholder="请输入助手名称" clearable />
        </el-form-item>
        <!-- <el-form-item label="微信ID" prop="wcId" v-if="!common">
          <el-input v-model="queryParams.wcId" @keyup.enter.native="handleQuery" placeholder="请输入微信ID" clearable />
        </el-form-item> -->
        <el-form-item label="所属人员" prop="wcId" v-if="!common">
            <el-select style="width: 120px;" v-if="!qommon"
              v-model="queryParams.deptId"
              @change="getDept"
              placeholder="请选择区域"
              clearable
            >
              <el-option
                v-for="dict in deptName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-autocomplete style="width: 160px;"
              class="my-autocomplete"
              v-model="param.lable"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
            ></el-autocomplete>
            <!-- <el-select
              filterable
              v-model="param.wcId"
              placeholder="请选择助手"
              clearable
            >
              <el-option
                v-for="dict in userName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <!-- <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入助手微信名称" clearable/> -->
        </el-form-item>
        <el-form-item label="登录时间" prop="loginTime">
          <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="归属地" prop="region">
          <el-input v-model="queryParams.region" @keyup.enter.native="handleQuery" placeholder="请输入归属地" clearable />
        </el-form-item>
        <el-form-item label="登录状态" prop="olState">
          <el-select v-model="queryParams.olState" placeholder="请选择登录状态 " clearable>
            <el-option v-for="dict in dict.type.sys_login_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button style="color: #fff;background-color: #0078fb;border-color: #0078fb;" plain icon="el-icon-upload2"  size="mini" @click="handleExport">批量导出</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="wcUserInfoList" :header-cell-style="{ background: '#fcfcfd', color: '#000' }"
      :border="false" @selection-change="handleSelectionChange"  @select-all="handleSelectAll">
      <el-table-column label="全选" type="selection" width="55" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="微信名称" prop="wcName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="最新登录时间" prop="loginTime" align="center" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="微信ID" prop="wcId" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="地区/部门" prop="deptName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="岗位" prop="postName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="微信所属人员" prop="nickName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="登录状态" prop="olState" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_login_status" :value="scope.row.olState" />
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" class-name="small-padding fixed-width">
        <template slot="header">
          <span>微信号详情</span>
          <el-tooltip class="item" effect="dark" content="进入操作" placement="top">
            <i class="el-icon-warning" style="color:#818e96;"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span style="color:#0078fb;cursor: pointer;" @click="golink(scope.row)">详情</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import request from '@/utils/request'
import nabars from '../components/nabar.vue'
import mathNum from "../components/daily.js"
import topIndex from '../components/top-index.vue'
import { listDept } from "@/api/system/dept";
import { listWcUser } from "@/api/system/user";
export default {
  name: "WcUserInfo",
  dicts: ['sys_login_status'],
  components: {
    nabars,
    topIndex,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectAll:false,
      selection:[],
      // 用户微信表格数据
      wcUserInfoList: [],
      //wcUserInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      chatTime: [],
      param:{
        wcId: null,
        lable:null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wcId: null,
        deptId:null,
        wcName: null,
        nickName: null,
        region: null,
        beginTime: null,
        endTime: null,
        loginState: null,
      },
      userParams: {
        pageNum: 1,
        pageSize: 9999,
        deptId: undefined,
      },
      common:false,
      qommon:false,
      deptName:[],
      userName:[],
      indexCount: [{ name: '今日登录', num: 0, type: 1, bili: 0 }, { name: '今日未登录', num: 0, type: 1, bili: 0 }, { name: '最新注册', num: 0, type: 1, bili: 0 }],
    };
  },
  created() {
    if (this.$store.state.user.roles.includes("common")) {
      this.common = true;
      this.qommon=true;
    }
    if (this.$store.state.user.roles.includes("qxleader")) {
      this.common = false;
      this.qommon=true;
    }
    if(!this.qommon){
      var deptName=[]
      listDept().then(response => {
        if(response.code==200){
          response.data.forEach((item) =>{
            deptName.push({value:item.deptId,label:item.deptName})
          })
          this.deptName=deptName
        }
      });
    }else{
      var userName=[]
      this.userParams=null
      listWcAssist(this.userParams).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          dt["records"].forEach((element) => {
            // userName.push({value:element.wcId,label:element.wcName})
            userName.push({value:element.wcName,label:element.wcId})
          });
        }
        this.userName=userName
      });
    }
  },
  mounted() {
    //console.log(this.$store.state.user.permissions)
    //this.loading=false
    this.getList();
    this.dayChanges()
  },
  methods: {
    golink(row) {
      //console.log(row,'查看');
      this.$router.push({ path: "/market/friend", name: 'friend', query: {wxid:row.wcId,userid:row.assistId} }).catch(() => { });
    },
    /** 查询用户微信列表 */
    getList() {
      this.loading = true;
      var param=this.queryParams
      if(this.param.wcId!=null){
        param.wcId=this.param.wcId
      }
      listWcUserInfo(param).then(res => {
        //console.log(res)
        if (res['success']) {
          const dt = res['data'];
          this.total = dt['total'];
          this.wcUserInfoList = dt['records'];
        }
        this.loading = false;
      });
      setTimeout(()=>{
        this.loading = false;
      },2000)
    },
    dayChanges(){
      getLogins().then(res=>{
          if(res.code==200){
            this.indexCount[0].type=mathNum(res.data.countT,res.data.countY).split('_')[0]
            this.indexCount[0].bili=mathNum(res.data.countT,res.data.countY).split('_')[1]
            this.indexCount[0].num=res.data.countT

            this.indexCount[1].type=mathNum(res.data.countTnot,res.data.countYnot).split('_')[0]
            this.indexCount[1].bili=mathNum(res.data.countTnot,res.data.countYnot).split('_')[1]
            this.indexCount[1].num=res.data.countTnot
          }
      })
      getNewRegister().then(res=>{
        if(res.code==200){
            this.indexCount[2].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
            this.indexCount[2].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
            this.indexCount[2].num=res.data.new_size
          }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      if(this.chatTime != '' && this.chatTime != null) {
        this.queryParams.beginTime = this.chatTime[0]+' 00:00:00'
        this.queryParams.endTime = this.chatTime[1]+' 23:59:59'
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime=[]
      this.queryParams.deptId=null
      this.param.wcId=null
      this.param.lable=null
      this.userParams= {
        pageNum: 1,
        pageSize: 9999,
        deptId: undefined,
      }
      this.handleQuery();
    },
    getDept(value) {
      //console.log(value)
      if(value!=''){
        this.userParams.deptId=value
        this.queryParams.wcId=null
        var userName=[]
        listWcUser(this.userParams).then((res) => {
          //console.log(res)
            if (res["code"]==200) {
            const dt = res["rows"];
            dt.forEach((element) => {
              if(this.userParams.deptId==100){
                if(element.deptId==100&&element.wcId!=''&&element.wcId!=null){
                  // userName.push({value:element.wcId,label:element.nickName})
                  userName.push({value:element.nickName,label:element.wcId})
                }
              }else if(element.wcId!=''&&element.wcId!=null){
                // userName.push({value:element.wcId,label:element.nickName})
                userName.push({value:element.nickName,label:element.wcId})
              }
            });
          }
          this.userName=userName
        });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectAll=false
      this.ids = selection.map(item => item.id)
      this.selection=selection
    },
    handleSelectAll(selection){
      this.selectAll=false
      if(selection!=''){
          this.ids=selection.map(item => item.id)
          this.selectAll=true
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.ids==''){
        this.$message({
            message: '请选择要导出的数据！',
            type: 'warning'
        });
        return
      }
      if(this.selectAll){
        this.download('arbit/wcuser_info/export', {
           ...this.queryParams
        }, `zhushou_${new Date().getTime()}.xlsx`)
      }else{
          this.exportExcel()
      }

    },
    exportExcel() {
        const data = [["id","微信名称", "最新登录时间", "微信ID","地区/部门", "微信所属人员", "登录状态"],];
        this.selection.forEach(element => {
          var arr=[element.id,element.wcName,element.loginTime,element.wcId,element.deptName,element.nickName,element.olState==0?'离线':'在线']
          data.push(arr)
        });

        // 将数据转换为工作表
        const ws = XLSX.utils.aoa_to_sheet(data);

        // 创建工作簿并添加工作表
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

        // 生成Excel文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        // 字符串转ArrayBuffer
        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }

        // 保存文件
        saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `zhushou_${new Date().getTime()}.xlsx`);
    },
    querySearch(queryString, cb) {
      var restaurants = this.userName;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.param.lable=item.value
      this.param.wcId=item.label
    },
  }
};

/** js请求 调用 */

// 查询用户微信列表
export function listWcUserInfo(query) {
  return request({
    url: '/arbit/wcuser_info/page',
    method: 'get',
    params: query
  })
}

// 查询登录统计
export function getLogin(data) {
  return request({
    url: '/arbit/wcuser_info/dayOnli',
    method: 'post',
    data: data
  })
}

// 查询未登录统计
export function getNotLogin(data) {
  return request({
    url: '/arbit/wcuser_info/dayNotOnli',
    method: 'post',
    data: data
  })
}

// 查询新注册统计
export function getNewRegister(data) {
  return request({
    url: '/arbit/wcuser_info/new_assist',
    method: 'post',
    data: data
  })
}
// 查询登录及未登录统计
export function getLogins() {
  return request({
    url: '/arbit/wcuser_info/GetOnliCount',
    method: 'get',
  })
}
// 查询助手信息列表
export function listWcAssist(query) {
  return request({
    url: "/arbit/wcuser_info/page",
    method: "get",
    params: query,
  });
}
</script>
<style scoped lang="scss">
.app-container {
  background-color: #f6f9fb;
}
.my-autocomplete {width: 160px;}
.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;

  .from-item {
    display: flex;
    flex-wrap: wrap;
  }

  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}
.blue-button {
      color: #fff;
      background-color: #0078fb;
      border-color: #0078fb;
}
</style>
